import React from 'react';
import {
    Button,
    Text,
    View,
    Image,
    StyleSheet,
    Dimensions,
    StatusBar,
    ActivityIndicator,
    FlatList,
    ScrollView,
    RefreshControl,
    Animated,
    TouchableHighlight,
    TouchableOpacity,
    Clipboard,
    Modal,
    Linking,
    PermissionsAndroid,
    ToastAndroid
} from 'react-native';
import Swiper from 'react-native-swiper';
import { MarqueeHorizontal, MarqueeVertical } from 'react-native-marquee-ab';
import styles from './styles';
import AsyncStorage from "@react-native-community/async-storage";

import JPush from 'jpush-react-native';

const { width, height } = Dimensions.get('window')

import app from '../../../app.json';
import Ugame from '../../../Ugame';
import Httpc from "../../utils/Httpc";
import REQUEST from "../../../REQUEST";
import Utils from "../../utils/Utils";

export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            moreModalVisible: false,
            base_img: {},
            data: [],
            loaded: false,
            refreshing: false,
            shopname: '小店',
            shoptitle: '店铺公告',
            site: {},
            news: [],
            wins: [],
            gmlist: [],
        };
        // 在ES6中，如果在自定义的函数里使用了this关键字，则需要对其进行“绑定”操作，否则this的指向会变为空
        // 像下面这行代码一样，在constructor中使用bind是其中一种做法（还有一些其他做法，如使用箭头函数等）
        //this.getBaseHomeImg = this.getBaseHomeImg.bind(this);
        //this.getSiteInfo=this.getSiteInfo.bind(this);
    }
    static navigationOptions = {
        title: '首页',
        header: null,  //隐藏顶部导航栏
        //tabBarVisible: false, // 隐藏底部导航栏
        headerStyle: {
            backgroundColor: '#f4511e',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
            fontWeight: 'bold',
        },
    }
    GetRootID(){
        Httpc.get(REQUEST.GetRootID, {key:app.rootidKey}, (res) => {
            app.rootid = res.rootid;
            this.getBaseHomeImg();
            this.getSiteInfo();
        })
    }
    componentDidMount() {
        JPush.init();
        this.requestMultiplePermission();
        this.GetRootID();



        //连接状态
        // this.connectListener = result => {
        //     console.log("connectListener:" + JSON.stringify(result))
        // };
        // JPush.addConnectEventListener(this.connectListener);
        // //通知回调
        // this.notificationListener = result => {
        //     console.log("notificationListener:" + JSON.stringify(result))
        // };
        // JPush.addNotificationListener(this.notificationListener);
        // //本地通知回调
        // this.localNotificationListener = result => {
        //     console.log("localNotificationListener:" + JSON.stringify(result))
        // };
        // JPush.addLocalNotificationListener(this.localNotificationListener);
        // //自定义消息回调
        // this.customMessageListener = result => {
        //     console.log("customMessageListener:" + JSON.stringify(result))
        // };
        // JPush.addCustomMessagegListener(this.customMessageListener);
        // //tag alias事件回调
        // this.tagAliasListener = result => {
        //     console.log("tagAliasListener:" + JSON.stringify(result))
        // };
        // JPush.addTagAliasListener(this.tagAliasListener);
        // //手机号码事件回调
        // this.mobileNumberListener = result => {
        //     console.log("mobileNumberListener:" + JSON.stringify(result))
        // };
        // JPush.addMobileNumberListener(this.mobileNumberListener);
    }
    async requestMultiplePermission() {
        try {
            const permissions = [             
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                PermissionsAndroid.PERMISSIONS.CAMERA
            ]
            //返回得是对象类型
            const granteds = await PermissionsAndroid.requestMultiple(permissions)
            var data = "是否同意地址权限: "
            if (granteds["android.permission.ACCESS_FINE_LOCATION"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }

            data = data+"是否同意相机权限: "
            if (granteds["android.permission.CAMERA"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            data = data+"是否同意存储权限: "
            if (granteds["android.permission.WRITE_EXTERNAL_STORAGE"] === "granted") {
                data = data + "是\n"
            } else {
                data = data + "否\n"
            }
            //this.show(data)
        } catch (err) {
            //this.show(err.toString())
        }
    }
    show(data) {
        ToastAndroid.show(data,ToastAndroid.SHORT)
    }
    getSiteInfo() {
        Httpc.get(REQUEST.site_info, { rootid: app.rootid }, function (res) {
            if (res.StatusCode == 1) {
                this.setState({
                    site: res.Data.site,
                    news: res.Data.news.rows,
                    wins: res.Data.wins.rows,
                    gmlist: res.Data.gmlist,
                    shopname: res.Data.site.shopname,
                    shoptitle: res.Data.site.shoptitle
                });
                Ugame.site = res.Data.site;
            }
        }.bind(this));
    }
    getBaseHomeImg() {
        Httpc.get(REQUEST.HOME_BASE_IMG, {}, (res) => {
            this.setState({
                base_img: res,
                loaded: true
            });
            Ugame.base_img = res;
        })
    }
    on_go_explanin(detailed) {
        this.props.navigation.navigate('Explain', {
            detailed: Httpc.imgPate(detailed),
        })
    }
    on_go_site() {
        let site = this.state.site;
        let logo =Httpc.imgPate(this.state.base_img.header.logo);
        this.props.navigation.navigate('Site', {
            site: site,
            logo: logo
        })
    }
    renderSwiper(swiper_ad) {
        var itemArr = [];
        for (var i = 0; i < swiper_ad.length; i++) {
            let data = swiper_ad[i];
            itemArr.push(
                <TouchableOpacity key={{ uri: data.image }} onPress={() => this._on_newsDeatiled(data.id)}>
                    <View>
                        <Image resizeMode="cover" style={styles.activityImg} source={{ uri: Httpc.imgPate(data.image) }} />
                    </View>
                </TouchableOpacity>
            );
        }
        return itemArr;
    }
    _onRefresh = () => {
        this.setState({ refreshing: true });
        Httpc.get(REQUEST.site_info, { rootid: app.rootid }, function (res) {
            if (res.StatusCode == 1) {
                this.setState({
                    site: res.Data.site,
                    news: res.Data.news.rows,
                    wins: res.Data.wins.rows,
                    gmlist: res.Data.gmlist,
                    shopname: res.Data.site.shopname,
                    shoptitle: res.Data.site.shoptitle,
                    refreshing: false
                });
            }
        }.bind(this));
    }
    on_go_live() {
        this.props.navigation.navigate('Live');
    }
    on_go_game(item) {
        //'FootballGame'
        this.props.navigation.navigate(item.Model, {
            Name: item.Name,
            CDownTime: item.CDownTime,
            Content: item.Content,
        });
    }
    _on_newsDeatiled = (id) => {
        this.props.navigation.navigate('NewsDetailed',{
            id:id
        });
    }
    _createNewsItem = ({ item }) => {
        return (
            <TouchableOpacity onPress={() => this._on_newsDeatiled(item.id)}>
                <View style={styles.recommend_lists}>
                    <View style={styles.recommend_lists_title}>
                        <View style={{ alignItems: 'flex-start', height: 65 }}>
                            <Text style={{ fontSize: 14 }}>{item.title}</Text>
                        </View>
                        <View style={styles.cate}>
                            <Text style={{ fontSize: 12, color: '#999999' }}>{item.GameName}</Text>
                            <Text style={{ fontSize: 12, color: '#999999', width: 60, height: 14, overflow: 'hidden' }}>{item.Ctime}</Text>
                        </View>
                    </View>
                    <Image style={styles.thumb} source={{ uri: item.headimage }} />
                </View>
            </TouchableOpacity>
        );
    }
    _creategmlistItem({ item }) {
        const PicAddr = Httpc.imgPate(item.PicAddr);
        Ugame.gmlist[item.id] = item;
        Ugame.gmlist[item.id].PicAddr = PicAddr;
        const Title = item.Title.split("|");
        let css = {};
        if (!!Title[0]) {
            css = styles.itemtips1;
        } else {
            css = styles.itemtips2;
        }
        return (
            <TouchableOpacity style={styles.category_item} onPress={() => this.on_go_game(item)}>
                <View >
                    <Image resizeMode="cover" style={styles.category_item_img} source={{ uri: PicAddr }} />
                    <Text style={styles.category_item_text}>{item.Name}</Text>
                    {/* <Text style={[css, { backgroundColor: Title[0] }]}>{Title[1]}</Text> */}
                </View>
            </TouchableOpacity>
        );
    }
    on_go_FollowLists = () => {
        this.props.navigation.navigate('FollowList', {

        });
    }
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <View style={{
                    flex: 1, justifyContent: 'center', flexDirection: 'row',
                    justifyContent: 'space-around',
                    padding: 10
                }}>
                    <ActivityIndicator size="large" color="#d0162e" />
                </View>

            </View>
        );
    }
    hide_more_model = () => {
        this.setState({
            moreModalVisible: false
        });
    }
    renderWx = () => {
        return (
            <Modal
                animationType="fade"
                transparent={true}
                visible={this.state.moreModalVisible}
                presentationStyle='overFullScreen'
                onRequestClose={() => {
                    this.hide_more_model()
                }}
            >
                <View style={styles.more_model}>
                    <View style={styles.more_model_content}>
                        <View style={styles.more_model_header}>
                            <Image resizeMode="cover" style={{ marginTop: 5, marginBottom: 5 }} source={require('../../image/js_img_icon_wx.png')} />
                            <Text style={{ fontSize: 12, color: '#666666', paddingBottom: 5 }}>复制成功</Text>
                            <Text style={{ fontSize: 12, color: '#969696', paddingBottom: 5 }}>微信搜索添加店主好友</Text>
                        </View>
                        <View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center', width: width - 150, borderTopColor: '#e5e5e5', borderTopWidth: 0.5 }} >
                            <TouchableOpacity style={styles.ball_addr_operation} onPress={this.hide_more_model}>
                                <Text style={[styles.btn_item, { padding: 10 }]}>
                                    我知道了
                                </Text>
                            </TouchableOpacity >
                        </View>
                    </View>
                </View>
            </Modal>
        );
    }
    on_copy_wx = (wxchart) => {
        Clipboard.setString(wxchart);
        this.setState({
            moreModalVisible: true
        });
    }
    do_tel = (phone) => {
        let tel = 'tel:' + phone// 目标电话
        Linking.canOpenURL(tel).then((supported) => {
            if (!supported) {
                console.log('Can not handle tel:' + tel)
            } else {
                return Linking.openURL(tel)
            }
        }).catch(error => console.log('tel error', error))

    }
    render() {
        let { news, gmlist, wins, site } = this.state;
        if (!this.state.loaded || !this.state.base_img) {
            return this.renderLoadingView();
        }
        const header = this.state.base_img.header;
        const menu = this.state.base_img.menu;
        const swiper_ad = this.state.base_img.swiper_ad;
        const bottom_ad = this.state.base_img.bottom_ad;
        const shopname = this.state.shopname;
        const shoptitle = this.state.shoptitle;
        const logo = Httpc.imgPate(this.state.site.shopimage);
        let Mqwins = [];
        for (let i = 0; i < wins.length; i++) {
            Mqwins.push({
                label: i,
                value: '恭喜' + Utils.plusXing(wins[i].phone, 3, 6) + wins[i].ud_Note + '中' + wins[i].ud_NowCoin + '元'
            });
        }
        return (
            <View style={styles.container}>
                <StatusBar translucent={true} backgroundColor="transparent" />
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this._onRefresh}
                        />
                    }
                >
                    <Image resizeMode="cover" style={styles.index_bj} source={{ uri: Httpc.imgPate(header.bg) }} />
                    <View style={styles.head}>
                        <Image resizeMode="cover" style={styles.defoult_logo} source={{ uri: logo }} />
                        <View style={styles.head_info}>
                            <Text style={{ fontSize: 16, color: '#ffffff' }}>欢迎加入{shopname}</Text>
                            <Text style={{ color: '#ffffff', fontSize: 12 }}>店铺公告：{shoptitle}</Text>
                            <View style={styles.shareicon}>
                                <TouchableOpacity onPress={() => this.do_tel(site.phone)}>
                                    <Image resizeMode="cover" style={styles.icon_item} source={require('../../image/js_img_index_dh.png')} />
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this.on_copy_wx(site.wxchart)}>
                                    <Image resizeMode="cover" style={styles.icon_item} source={require('../../image/js_img_index_wx.png')} />
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this.on_go_site()}>
                                    <Image resizeMode="cover" style={styles.icon_item} source={require('../../image/js_img_index_ewm.png')} />
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <View style={styles.remind}>
                        <Image resizeMode="cover" style={styles.remindImg} source={require('../../image/js_img_gg_icon.png')} />
                        <View style={styles.marqueeVerticalView}>
                            <MarqueeVertical
                                textList={Mqwins}
                                width={width - 40}
                                height={30}
                                direction={'up'}
                                delay={10000}
                                numberOfLines={1}
                                bgContainerStyle={{ backgroundColor: '#ffffff' }}
                                textStyle={{ color: '#f59d37', fontSize: 12 }}
                                onTextClick={(item) => {
                                    //alert(''+JSON.stringify(item));
                                }}
                            />
                        </View>
                    </View>
                    <View style={styles.menulist}>
                        <TouchableOpacity onPress={() => this.on_go_live()}>
                            <View style={styles.menulistitem}>
                                <Text style={{ fontSize: 16, color: '#d9b42a', marginBottom: 10 }}>比分直播</Text>
                                <Image resizeMode="cover" style={{ height: 45, width: 69 }} source={{ uri: Httpc.imgPate(menu[1].icon) }} />
                            </View>
                        </TouchableOpacity >
                        <TouchableOpacity onPress={() => this.on_go_FollowLists()}>
                            <View style={styles.menulistitem}>
                                <Text style={{ fontSize: 16, color: '#ff0000', marginBottom: 10 }}>跟单大厅</Text>
                                <Image resizeMode="cover" style={{ height: 45, width: 69 }} source={{ uri: Httpc.imgPate(menu[2].icon) }} />
                                <Text style={styles.menulisttips}>进行中</Text>
                            </View>
                        </TouchableOpacity >
                    </View>
                    <View style={styles.activity}>
                        <Swiper
                            style={styles.wrapper}
                            showsButtons={false} // 分页风格
                            paginationStyle={styles.paginationStyle}
                            // 点样式
                            dotStyle={styles.dotStyle}
                            // 活动点样式
                            activeDotStyle={styles.activeDotStyle}
                        >
                            {this.renderSwiper(swiper_ad)}
                        </Swiper>
                    </View>
                    <View style={styles.category}>
                        <FlatList
                            data={gmlist}
                            horizontal={false}
                            numColumns={3}
                            keyExtractor={(item, index) => index.toString()}
                            renderItem={({ item }) => this._creategmlistItem({ item })}
                        />
                    </View>
                    <View style={styles.news}>
                        <View style={styles.news_title}>
                            <Text style={styles.news_title_tips}>资讯快报</Text>
                        </View>
                        <FlatList
                            data={news}
                            keyExtractor={(item, index) => index.toString()}
                            renderItem={this._createNewsItem}
                        />
                    </View>
                    <TouchableOpacity onPress={() => this.on_go_explanin(bottom_ad.detailed)}>
                        <View style={{ marginTop: 8 }}>
                            <Image resizeMode="cover" style={styles.activityImg} source={{ uri: Httpc.imgPate(bottom_ad.image) }} />
                        </View>
                    </TouchableOpacity>
                </ScrollView>
                {this.renderWx()}
            </View>
        );
    }

}
